<?php

declare(strict_types=1);

namespace app\yperp\command;

use DateTime;
use Facebook\WebDriver\Exception\NoSuchWindowException;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Fastposter\Client as FastposterClient;
use think\console\Command;
use think\console\Input;

use think\console\Output;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Stream;
use InvalidArgumentException;
use RuntimeException;
use think\Db;
use think\facade\Cache;

class suosi1 extends Command
{

    protected $output;

    protected $input;
    protected $driver;
    protected $windows = [];
    protected $cookies = [];

    protected $token = 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2luZm8iOiIlN0IlMjJhdmF0YXIlMjIlM0ElMjJodHRwcyUzQSUyRiUyRndld29yay5xcGljLmNuJTJGd3dwaWMzYXolMkY5OTU3ODZfTnc0YXFZZEZTamFHbmpVXzE3MTYyNzc3MzMlMkYwJTIyJTJDJTIyY29ycElkJTIyJTNBJTIyd3cyYjFhOGVkZGIzMjcyZmZiJTIyJTJDJTIyaW5kdXN0cnlUeXBlJTIyJTNBJTIybXl0eGwlMjIlMkMlMjJsb2dpblR5cGUlMjIlM0ElMjJub3JtYWwlMjIlMkMlMjJtZW1iZXJJZCUyMiUzQTE3NjA5Mjg5MjA1MjY1ODAxMTMlMkMlMjJtZW1iZXJOYW1lJTIyJTNBJTIyJUU2JTlEJThFJUU0JUI4JTk2JUU1JUI5JUIzJTIyJTJDJTIybW9iaWxlJTIyJTNBJTIyMTg5ODExNDAxMDElMjIlMkMlMjJvcmdJZCUyMiUzQTEwMDAxMCUyQyUyMm9yZ05hbWUlMjIlM0ElMjIlRTklOTUlQkYlRTglOTklQjklRUYlQkMlODglRTYlOTklQkElRTYlOTglOTMlRTUlQUUlQjYlRUYlQkMlODklMjIlMkMlMjJvcmdUeXBlJTIyJTNBJTIyZ2VuZXJhbCUyMiUyQyUyMnJlZ2lvbkNvZGUlMjIlM0ElMjIwMDAwMDAwMDAwMDAwMDAwMDAlMjIlMkMlMjJzaG9ydE5hbWUlMjIlM0ElMjIlRTYlOTklQkElRTYlOTglOTMlRTUlQUUlQjYlMjIlMkMlMjJ1c2VySWQlMjIlM0ExNzYwOTI4OTIwNTI2NTgwMTEzJTJDJTIydXNlck5hbWUlMjIlM0ElMjIlRTYlOUQlOEUlRTQlQjglOTYlRTUlQjklQjMlMjIlMkMlMjJ1c2VyVHlwZSUyMiUzQSUyMmVtcGxveWVlJTIyJTdEIiwidXNlcl9uYW1lIjoiMTAwMDEwOzE3NjA5Mjg5MjA1MjY1ODAxMTM7ZW1wbG95ZWU7bm9ybWFsIiwib3JnX2lkIjoxMDAwMTAsInNjb3BlIjpbImFsbCJdLCJleHAiOjE3MjQzNzY1MzYsImp0aSI6IjBjZTlhNmQ3LWIwNDgtNDlmZS05YjkwLTljOWM3YzlhODNlNCIsImNsaWVudF9pZCI6InByb2R1Y3Rpb24ifQ.oELIeFt774ZgV-NDlJarV3uC4iOM9tyc7OVeL_cHUSL6eQpQP5Xxpqns_CWuBLfRaimxrR6PLw-YRb421HIxc71z5UoEXaLTjANN0ly4EMwLpbR6IYyg02w6cetYg4lSwM4K98j0QmW5u3K-L2_YK5LwJZAP-XfapfUBwSNrh6A';

    public $grpup_ids = [
        '合肥' => '1793135207802933249',
        '成都' => '1784914950324916225',
        '绵阳' => '1784915354635022338',
        '重庆' => '1772508002709778434',
        '虹创' => '1763088628184178690',
    ];
    protected function configure()
    {
        // 指令配置
        $this->setName('suosi')
            ->setDescription('批量创建群活码');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $this->input = $input;

        $this->output = $output;


        $this->go();
    }
    function go()
    {
        $users = Db::table('dp_suosi_user1')

            // ->where('username', '吕阳丽')
            // ->where('dep_name', '苏宁大都会店')
            // ->whereNotNull('group_qr')
            ->where('group_qr_status', 0)
            // ->limit(1)
            // ->order('id desc')
            ->select();

        foreach ($users as $user) {
            $param = [
                'shopname' => $user['dep_name'],
                'name' => $user['username'],
                'dept_type' => $user['dep'] . $user['dep_type'] . '中心',
                'groupName' => $user['dep_name'],
                'dep' => $user['dep'],
                'BaseName' => '长虹美菱会员福利群-' . $user['dep_name'],
            ];
            $data = $this->create_group_qr($param);
            dump($data);
            if ($data['success'] || $data['msg'] == '活码名称已存在') {
                $user = Db::table('dp_suosi_user1')->where(['id' => $user['id']])->update(['group_qr_status' => 1]);
                dump($user);
            } else {
                $user = Db::table('dp_suosi_user1')->where(['id' => $user['id']])->update(['group_qr_status' => 0, 'group_qr' => json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)]);
                dump($user);
            }
        }
    }
    function require($url = '', $json, $method = 'POST')
    {
        $client = new Client(['verify' => env('root_path') . 'application\yperp\common\cacert.pem',]);
        $headers = [
            'authorization' => $this->token,
            'content-type' => 'application/json;charset=utf-8'
        ];
        $body = json_encode($json);
        $request = new Request($method, $url, $headers, $body);
        $res = $client->sendAsync($request)->wait();
        $res = $res->getBody()->getContents();
        return json_decode($res, true);
    }

    public function search_group($keyword, $check_dept = '')
    {
        $check_dept = $check_dept !== '' ? $check_dept : $keyword;
        // $check_dept = '测试区群';
        // $keyword= '测试区群';
        dump([$keyword, $check_dept]);
        $url = 'https://m.suosishequ.com/gateway/user-center/select/component/search';
        $param = [
            "keyword" => $keyword,

            "types" => [
                "groupContacts"
            ],
            "selectTypeList" => [
                "user",
                "member",
                "group"
            ]
        ];
        $response = $this->require($url, $param);
        dump(['群' => $response]);
        $dataSource = $response['data']['dataSource'];
        $dataSource_find = [];

        foreach ($dataSource as $key => $value) {
            // dump([$value['extendedAttribute']['groupName'], $check_dept]);
            if ($value['extendedAttribute']['groupName'] == $check_dept) {
                $dataSource_find = $value;
            }
        }

        $response_data = [];
        if (!empty($dataSource_find)) {
            $response_data = [
                "id" => $dataSource_find['key'],
                "key" => $dataSource_find['key'],
                "name" => $dataSource_find['label'],
                "type" => "GROUP",
                "contactType" => 3,
                "extendedAttribute" => [
                    'wxUserId' => $dataSource_find['extendedAttribute']['wxUserId'],
                    // 'groupName' => $dataSource_find['groupName'],
                    'chatId' => $dataSource_find['extendedAttribute']['chatId'],
                    'totalMember' => $dataSource_find['extendedAttribute']['totalMember'],
                    'userName' => $dataSource_find['extendedAttribute']['userName'],
                    'userId' => $dataSource_find['extendedAttribute']['userId'],
                ],
                "childDelete" => true
            ];
        }
        return $response_data;
    }

    public function create_group_qr($params)
    {
        $tags = [];
        $shopname = $this->method_tag_search($params['shopname']);//'广元美天美电器有限公司'
        if (!empty($shopname)) {
            $tags[] = $shopname;
        }
        $name = $this->method_tag_search($params['name']);//杜明虹
        if (!empty($name)) {
            $tags[] = $name;
        }
        $dept_type = $this->method_tag_search($params['dept_type']); //绵阳冰洗中心
        if (!empty($dept_type)) {
            $tags[] = $dept_type;
        }

        $url = 'https://m.suosishequ.com/gateway/group/web/liveCode/group/save';
        $param = [
            "name" => $params['groupName'],
            "groupId" => $this->grpup_ids[$params['dep']],
            "groupSignature" => [$this->search_group($params['BaseName'])],
            "labelSignature" => $this->method_tag_create($tags)['data'],
            "autoCreateRoom" => 1,
            "roomBaseName" => $params['BaseName'], //我是群名称前缀
            "roomBaseId" => 1
        ];

        dump($param);
        $data = $this->require($url, $param);

        return $data;
    }

    public function method_tag_search($keyword = '杜明虹', $check_dept = '分部客户资产')
    {
        $url = 'https://m.suosishequ.com/gateway/user-center/select/component/search';
        $param = ['keyword' => $keyword, 'types' => ['customerTagContacts'], 'selectTypeList' => ['tag']];
        $response = $this->require($url, $param);

        $response_data = [];
        if (count($response['data']['dataSource']) > 0) {

            $dataSource = $response['data']['dataSource'];
            $dataSource_find = [];
            foreach ($dataSource as $key => $value) {
                if ($value['labelPathName'] !== $check_dept) {
                    continue;
                }
                if ($value['label'] == $keyword) {
                    $dataSource_find = $value;
                }
            }
            if (!empty($dataSource_find)) {
                $response_data = [
                    'id' => $dataSource_find['key'],
                    'key' => $dataSource_find['key'],
                    'name' => $dataSource_find['label'],
                    'type' => 'CUSTOMER_TAG',
                    'orgId' => '100010',
                    'contactType' => 9,
                    'childDelete' => true
                ];
            }

        }

        return $response_data;
    }


    public function method_tag_create($customerTagInfoList = [], $check_dept = '')
    {
        $url = 'https://m.suosishequ.com/gateway/user-center/select/component/result';
        $data = [
            'selectTypeList' => ['tag'],
            'tagTypeList' => [1],
            'labelPermission' => 1,
            'deptInfoList' => [],
            'userInfoList' => [],
            'groupInfoList' => [],
            'tagInfoList' => [],
            'customerTagInfoList' => $customerTagInfoList,
            'types' => ['customerTagContacts'],
            'weChatTagInfoList' => [],
            'customerManagerInfoList' => [],
            'managerUserInfoList' => [],
            'managerGroupInfoList' => [],
            'employeeCodeInfoList' => [],
            'groupTagInfoList' => [],
            'circlesTagInfoList' => [],
            'contentTagInfoList' => [],
            'equipmentInfoList' => [],
            'tvInfoList' => [],
            'maternalInfoList' => [],
            'cameraInfoList' => [],
            'workGroupInfoList' => [],
            'id' => '100010-' . $this->create_time_str(),
        ];

        dump($data);
        $data = $this->require($url, $data);
        return $data;
    }

    function create_time_str()
    {
        // 获取当前时间
        $date = new DateTime();
        $microseconds = sprintf("%06d", ($date->format("u")));

        // 格式化时间值
        $time_value = $date->format("YmdHis") . $microseconds;

        return $time_value;
    }


    function similar($string1, $string2)
    {
        similar_text($string1, $string2, $percent);
        return (int) $percent;
    }
}
